import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
let movedistance = 0;
Page({
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

    //判断用户是否登录
    Login: false,

  onShow() {
    var flag = wx.getStorageSync('userinfo');
    if(flag){
      this.Login = true
    }
    // 1 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    // 2 获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || [];
    this.setData({ address });
    this.setCart(cart);

  },
  // 点击 收货地址
  async handleChooseAddress() {
    //判断用户是否登录
    this.userLogin();
    var boolen = this.Login;
    if(boolen){
    try {
      // 1 获取 权限状态
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      // 2 判断 权限状态
      if (scopeAddress === false) {
        await openSetting();
      }
      // 4 调用获取收货地址的 api
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      // 5 存入到缓存中
      wx.setStorageSync("address", address);

    } catch (error) {
      console.log(error);
    }
  }
  },
  // 商品的选中
  handeItemChange(e) {
    // 1 获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    // 2 获取购物车数组 
    let { cart } = this.data;
    // 3 找到被修改的商品对象
    let index = cart.findIndex(v => v[0].goodId === goods_id);
    // 4 选中状态取反
    cart[index][0].checked = !cart[index][0].checked;
    this.setCart(cart);

  },
  // 设置购物车状态同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量
  setCart(cart) {
    let allChecked = true;
    // 1 总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v[0].checked) {
        totalPrice += v[0].num * v[0].goodPrice;
        totalNum += v[0].num;
      } else {
        allChecked = false;
      }
    })
    // 判断数组是否为空
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      cart,
      totalPrice, totalNum, allChecked
    });
    wx.setStorageSync("cart", cart);
  },
  // 商品全选功能
  handleItemAllCheck() {
    // 1 获取data中的数据
    let { cart, allChecked } = this.data;
    // 2 修改值
    allChecked = !allChecked;
    // 3 循环修改cart数组 中的商品选中状态
    cart.forEach(v => v[0].checked = allChecked);
    // 4 把修改后的值 填充回data或者缓存中
    this.setCart(cart);
  },
  // 商品数量的编辑功能
  async handleItemNumEdit(e) {

    // 1 获取传递过来的参数 
    const { operation, id } = e.currentTarget.dataset;
    // 2 获取购物车数组
    let { cart } = this.data;
    // 3 找到需要修改的商品的索引
    const index = cart.findIndex(v => v[0].goodId === id);
    // 4 判断是否要执行删除
    if (cart[index][0].num === 1 && operation === -1) {
      // 4.1 弹窗提示
      const res = await showModal({ content: "您是否要删除？" });
      if (res.confirm) {
        cart.splice(index, 1);
        this.setCart(cart);
      }
    } else {
      // 4  进行修改数量
      cart[index][0].num += operation;
      // 5 设置回缓存和data中
      this.setCart(cart);
    }
  },
  // 点击 生成订单 
  async handlePay(){

    //判断用户是否登录
    this.userLogin;
    var boolen = this.Login;
    if(boolen){
    // 1 判断收货地址
    const {address,totalNum}=this.data;
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"});
      return;
    }
    // 2 判断用户有没有选购商品
    if(totalNum===0){
      await showToast({title:"您还没有选购商品"});
      return ;
    }
    // 将选中的商品添加到缓存
    let cart = wx.getStorageSync('cart');
    let info = []
    for(var index in cart){
      if(cart[index][0].checked){
        info = info.concat(cart[index]) 
      }
    }
    wx.setStorageSync('order', info)
    wx.setStorageSync('allChecked', this.data.allChecked);
    // 3 跳转到 支付页面
    wx.navigateTo({
      url: '/pages/buy/buy'
    });
  }
  },

  //判断用户是否登录
  userLogin(){
    //判断用户是否登录
    var userinfo = wx.getStorageSync('userinfo');
    var that = this
    if(!userinfo){
      wx.showModal({
        title: '提示',
        content: '您还未登录，请登录！',
        success: function(res) {
        if (res.confirm) {
          wx.switchTab({
            url: '../my/my',
          })
        } else if (res.cancel) {
          that.Login = false;
        }
        }
        })
    }
  },

  // 手指触摸动作开始
  touchstartX(e) {
    // 获取触摸X坐标
    this.recordX = e.touches[0].clientX;
  },
  // 点击操作
  resetX() {
   this.slideAnimation(0, 500);
  },
  // 手指触摸后移动
  touchmoveX(e) {
   let currentX = e.touches[0].clientX;
   movedistance = currentX - this.recordX; // 获取移动距离
   this.slideAnimation(movedistance, 500);
  },
  // 手指触摸动作结束
  touchendX() {
    let recordX;
    if (movedistance <= -100) { // 移动达到距离就动画显示全部操作项
    recordX = -100;
    } else if (movedistance >= -100) { // 移动未达到距离即还原
    recordX = 0;
    }
    this.slideAnimation(recordX, 500);
  },
  // 滑动动画
  slideAnimation(recordX, time) {
    let animation = wx.createAnimation({
    duration: time,
    timingFunction: 'ease'
    });
    animation.translate(recordX + 'rpx', 0).step()
    this.setData({
    animation: animation.export()
    })
  },
   // 删除数据
 deleteItem() {
  let that = this;
  let address = wx.getStorageSync('address');
  wx.showModal({
   title: '提示',
   content: '是否删除该条数据？',
   success(res) {
    if (res.confirm) {
      wx.removeStorage({
        key: 'address'
        })
     that.slideAnimation(0, 500);
     that.setData({
      address: {}
     });
    } else if (res.cancel) {
     console.log('用户点击取消')
    }
   }
  });
 },

  onLoad: function(options) {
    wx.setNavigationBarTitle({
     title: '银行业务',
    });
    movedistance = 0; // 解决切换到其它页面再返回该页面动画失效的问题
   }
    
})